package org.example.carplatoon.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    public static final String SALT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
    private static final String ISS = "carplatoon";
    private static final long EXPIRATION_30_MINUTES = 1000 * 60 * 30 * 12;

    /**
     * 生成token
     * @param info={id, username}
     * @return
     */
    public static String createToken(Map<String, Object> info) {

        // HEADER
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        // PAYLOAD
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", info.get("id"));
        claims.put("userName", info.get("userName"));
        claims.put("phoneNum", info.get("phoneNum"));
        claims.put("idNumber", info.get("idNumber"));

        JwtBuilder jwt = Jwts.builder()
                .setIssuer(ISS)
                .setHeader(header)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_30_MINUTES))
                .signWith(SignatureAlgorithm.HS256, SALT);

        return jwt.compact();
    }

    /**
     * 验证token，返回数据只有id和username
     * @param JWT=String
     * @return {id,username}/null
     */
    public static Map<String, Object> checkToken(String JWT) {
        JWT = JWT.substring(7);
        Claims claims = null;
            claims = Jwts.parser()
                    .setSigningKey(SALT)
                    .parseClaimsJws(JWT)
                    .getBody();

        if (claims == null) {
            return null;
        }

        String username = (String) claims.get("userName");
        String id = (String) claims.get("id");
        String phoneNum = (String) claims.get("phoneNum");
        String idNumber = (String) claims.get("idNumber");
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", id);
        userInfo.put("userName", username);
        userInfo.put("phoneNum",phoneNum);
        userInfo.put("idNumber",idNumber);
        return userInfo;
    }
}
